package com.jc.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jc.vo.ApiConfig;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HttpPostUtil {

	private HttpPostUtil() {

	}

	public static final String SECRETID = "secretId";
	public static final String TIMESTAMP = "timestamp";
	public static final String SIGN = "sign";
	public static final String DATA = "data";
	public static final String DATALIST = "dataList";

	private static ObjectMapper om = new ObjectMapper();

	public static String send(String ecargoBodyJson, ApiConfig config, Boolean bodyIsList) throws IOException {
		String body = genBody(ecargoBodyJson, config, bodyIsList);
		System.out.println("请求参数body：" + body);
		String returnStr = httpSend(body, config.getServiceURL(),5000);
		return returnStr;
	}

	private static String genBody(String ecargoBodyJson, ApiConfig config, Boolean bodyIsList) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		 System.out.println("请求参数：" + ecargoBodyJson);
        String sstrXML = ecargoBodyJson;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String now = format.format(new Date());
        String secretId = config.getSecretId();
        String sign = SignUtil.generateSign(config,now);
        map.put(SECRETID, secretId);
		map.put(TIMESTAMP, now);
		map.put(SIGN, sign);
		if(bodyIsList) {
			map.put(DATALIST,sstrXML);
		} else {
			map.put(DATA, sstrXML);
		}
		return om.writeValueAsString(map);
	}

	public static String httpSend(String body, String serviceUrl,int timeout) throws IOException {
		String responseStr = "";

		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(serviceUrl);
			httpPost.setConfig(RequestConfig.custom().setSocketTimeout(timeout).build());
			StringEntity stringEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
			httpPost.setEntity(stringEntity);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					responseStr = EntityUtils.toString(entity, Charset.defaultCharset());
				}
				int code = response.getStatusLine().getStatusCode();
				if (code - 404 == 0 || code - 500 == 0) {
					responseStr = "{\"error\": \"Not Found\"}";
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseStr;
	}

}